<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\MjzjCrawlerService;
use Illuminate\Console\Command;

class CrawlMjzjCommand extends Command
{
    /**
     * 命令签名
     */
    protected $signature = 'mjzj:crawl 
                            {keywords : 搜索关键词，多个关键词用逗号分隔}
                            {--market= : 市场}
                            {--size=20 : 每页数量}
                            {--batch : 批量模式}';

    /**
     * 命令描述
     */
    protected $description = '爬取卖家之家评论者数据';

    /**
     * 执行命令
     */
    public function handle(MjzjCrawlerService $crawlerService): int
    {
        $keywords = $this->argument('keywords');
        $market = $this->option('market');
        $size = (int) $this->option('size');
        $batch = $this->option('batch');

        $this->info('开始爬取卖家之家数据...');

        if ($batch) {
            // 批量模式
            $keywordsList = array_map('trim', explode(',', $keywords));
            
            $this->info('批量爬取关键词: ' . implode(', ', $keywordsList));
            
            $results = $crawlerService->crawlBatch($keywordsList, $size);
            
            $totalCount = 0;
            foreach ($results as $keyword => $data) {
                $count = count($data);
                $totalCount += $count;
                $this->line("关键词 '{$keyword}': {$count} 条数据");
            }
            
            $this->info("批量爬取完成，总共获取 {$totalCount} 条数据");
        } else {
            // 单次模式
            $params = [
                'keywords' => $keywords,
                'market' => $market,
                'size' => $size,
            ];
            
            $this->info("爬取关键词: {$keywords}");
            
            $results = $crawlerService->searchReviewers($params);
            $count = count($results);
            
            $this->info("单次爬取完成，获取 {$count} 条数据");
        }

        // 显示统计信息
        $this->displayStats($crawlerService);

        return Command::SUCCESS;
    }

    /**
     * 显示统计信息
     */
    private function displayStats(MjzjCrawlerService $crawlerService): void
    {
        $this->newLine();
        $this->info('=== 数据统计 ===');
        
        $stats = $crawlerService->getStats();
        
        $this->table(
            ['统计项', '数值'],
            [
                ['总评论者数量', $stats['total_reviewers']],
                ['活跃评论者数量', $stats['active_reviewers']],
                ['平均评分', round($stats['avg_rating'], 2)],
                ['平均评论数', round($stats['avg_reviews'], 0)],
            ]
        );

        if (!empty($stats['top_platforms'])) {
            $this->newLine();
            $this->info('=== 热门平台 ===');
            $platformData = [];
            foreach ($stats['top_platforms'] as $platform) {
                $platformData[] = [$platform['platform'], $platform['count']];
            }
            $this->table(['平台', '数量'], $platformData);
        }
    }
} 